package com.ruoyi.framework.web.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.LogisticsStatusConstants;
import com.ruoyi.common.constant.PaymentStatusConstants;
import com.ruoyi.common.core.domain.DTO.*;
import com.ruoyi.common.core.domain.entity.Products;
import com.ruoyi.common.core.domain.entity.PurchaseRecords;
import com.ruoyi.common.core.domain.entity.UserPoints;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.zfb.AlipayFundTransUniTransferWap;
import com.ruoyi.common.utils.zfb.AlipayTradeAppPay;
import com.ruoyi.common.utils.zfb.AlipayTradeWapPay;
import com.ruoyi.system.mapper.PurchaseRecordMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class PurchaseRecordService {
    @Autowired
    private PurchaseRecordMapper purchaseRecordMapper;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private AlipayTradeAppPay alipayTradeAppPay;
    @Autowired
    private AlipayTradeWapPay alipayTradeWapPay;
    @Autowired
    private ProductService productService;

    //支付宝APP支付接口
    public AlipayTradeAppPayResponse appPayment(PurchaseRecordBO purchaseRecordBO) {
        //保存购买记录并构造支付宝支付参数
        TradeAppPayBO tradeAppPayBO = savePurchaseRecords(purchaseRecordBO);
        //调用支付宝APP支付
        try {
            return alipayTradeAppPay.tradeAppPay(tradeAppPayBO);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    //支付宝网页支付接口
    public AlipayTradeWapPayResponse wapPayment(PurchaseRecordBO purchaseRecordBO) {
        //保存购买记录并构造支付宝支付参数
        TradeAppPayBO tradeAppPayBO = savePurchaseRecords(purchaseRecordBO);
        //调用支付宝APP支付
        try {
            return alipayTradeWapPay.tradeWapPay(tradeAppPayBO);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    //保存购买记录并返回支付宝调用参数
    public TradeAppPayBO savePurchaseRecords(PurchaseRecordBO purchaseRecordBO){
        //保存购买记录
        PurchaseRecords purchaseRecords = new PurchaseRecords();
        BeanUtils.copyProperties(purchaseRecordBO, purchaseRecords);
        purchaseRecords.setStatus(1);
        Date date = new Date();
        purchaseRecords.setCreatedAt(date);
        purchaseRecords.setUpdatedAt(date);
        purchaseRecords.setPaymentStatus(0);
        purchaseRecords.setPaymentMethod(1);
        String orderNo = generateOrderNo();
        purchaseRecords.setOrderNo(orderNo);
        purchaseRecords.setLogisticsStatus(0);
        purchaseRecordMapper.insertPurchaseRecord(purchaseRecords);
        //根据商品id查询商品信息
        Products products = productService.selectProductById(purchaseRecordBO.getProductId());
        //构造支付宝支付参数
        TradeAppPayBO tradeAppPayBO = new TradeAppPayBO();
        tradeAppPayBO.setOrderNo(orderNo);
        tradeAppPayBO.setSubject(products.getName());
        tradeAppPayBO.setTotalAmount(purchaseRecordBO.getTotalAmount());
        return tradeAppPayBO;
    }

    //查询用户购买记录
    public List<PurchaseRecordVO> selectUserPurchaseRecord(SelectUserPurchaseRecordBO selectUserPurchaseRecordBO) {
        return purchaseRecordMapper.selectPurchaseRecordByUserId(selectUserPurchaseRecordBO);
    }

    //管理员查看所有订单
    public PageInfo<PurchaseRecordVO> selectPurchaseRecord(SelectPurchaseRecordBO selectPurchaseRecordBO) {
        Integer pageNum = selectPurchaseRecordBO.getPageNum();
        Integer pageSize = selectPurchaseRecordBO.getPageSize();
        // 配置分页插件后使用
        PageHelper.startPage(pageNum, pageSize);
        List<PurchaseRecordVO> purchaseRecordVOS = purchaseRecordMapper.selectPurchaseRecord(selectPurchaseRecordBO);
        return new PageInfo<>(purchaseRecordVOS);
    }

    //查询用户支付成功的订单数量
    public Integer selectPayCountByUserId(Long userId) {
        return purchaseRecordMapper.selectPayCountByUserId(userId);
    }

    //更新快递单号
    public void updateTrackingNumber(UpdateTrackingNumberBO updateTrackingNumberBO) {
        purchaseRecordMapper.updateTrackingNumber(updateTrackingNumberBO.getId(),updateTrackingNumberBO.getTrackingNumber());
    }

    //用户确认收货
    public void confirmReceipt(ConfirmReceiptBO confirmReceiptBO){
        purchaseRecordMapper.confirmReceipt(confirmReceiptBO);
    }

    //支付宝支付回调
    public void callback(Map<String, String> paramsMap) {
        String orderNo = paramsMap.get("out_trade_no");
        String trade_status = paramsMap.get("trade_status");
        //检验是否支付成功
        if (StringUtils.isEmpty(trade_status) || !trade_status.equals("TRADE_SUCCESS")) {
            purchaseRecordMapper.updateByOrderNo(orderNo, PaymentStatusConstants.PAY_FAIL, LogisticsStatusConstants.UNPAID);
            throw new BusinessException("支付失败");
        }
        //更新支付状态和物流状态
        purchaseRecordMapper.updateByOrderNo(orderNo,PaymentStatusConstants.PAY_SUCCESS,LogisticsStatusConstants.WAIT_FOR_SHIPMENT);
        //根据订单号查询用户id
        Long userId = purchaseRecordMapper.selectUserIdByOrderNo(orderNo);
        if (ObjectUtils.isEmpty(userId)) {
            throw new BusinessException("用户id为空");
        }
        //购买商品后成为会员
        UserPoints userPoints = pointsService.selectUserPointsByUserId(userId);
        userPoints.setLevel(2);
        pointsService.updateUserPoints(userPoints);
    }

    private String generateOrderNo() {
        // 使用Snowflake算法生成唯一ID，然后补0到18位
        long timestamp = System.currentTimeMillis();
        long nodeId = 1L; // 节点ID
        long sequence = (long) (Math.random() * 1000); // 序列号

        String orderNo = String.valueOf((timestamp << 22) | (nodeId << 12) | sequence);
        // 确保是18位
        while (orderNo.length() < 18) {
            orderNo = "0" + orderNo;
        }
        return orderNo.length() > 18 ? orderNo.substring(0, 18) : orderNo;
    }
}
